package com.h3c.nem.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.h3c.nem.dto.PageQueryDTO;
import com.h3c.nem.dto.mapstruct.NewWorkerDTO;
import com.h3c.nem.entity.*;
import com.h3c.nem.enums.CareInfoType;
import com.h3c.nem.mapper.TbCareEncourageMapper;
import com.h3c.nem.mapper.TbCareInfoMapper;
import com.h3c.nem.service.CommService;
import com.h3c.nem.service.ITbCareEncourageService;
import com.h3c.nem.utils.AppBusinessException;
import com.h3c.nem.utils.WeChatUtils;
import com.h3c.nem.vo.TbCareEncourageVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 新员工鼓励Service
 *
 * @author z22968
 * @date 2022/6/17 14:42
 */
@Slf4j
@Service
public class TbCareEncourageServiceImpl extends ServiceImpl<TbCareEncourageMapper, TbCareEncourage> implements ITbCareEncourageService {
    @Resource
    private CommService commService;
    @Resource
    TbCareInfoMapper tbCareInfoMapper;
    @Resource
    TbOfferWorkerServiceImpl tbOfferWorkerService;
    @Resource
    SdDeptServiceImpl sdDeptService;
    @Resource
    TbCareEncourageMapper tbCareEncourageMapper;
    @Resource
    private WeChatUtils weChatUtils;
    @Resource
    TbCareNoticeSettingServiceImpl tbCareNoticeSettingService;

    @Value("${care.receive.url}")
    private String careReceiveUrl;


    @Override
    public PageInfo<NewWorkerDTO> getEncourageList(PageQueryDTO<TbCareEncourageVO> pageQuery) {
        // TODO TEST
        Page<NewWorkerDTO> page = PageHelper.startPage(pageQuery.getPageNum(), pageQuery.getPageSize());
        // 1 获取操作人
        String userId = commService.getLoginUserId();
        SdAllWorker oldWorker = commService.getAllWorkerDoFromLocalCache(userId);
        // 2. 获取鼓励表中已经鼓励的用户 select new_worker_id from tb_care_encourage tce where tce.old_worker_id = userId
        // 3. 获取careInfo中已发送通知但未鼓励的用户 select * from tb_care_info tci where tci.old_worker_id = userId and tci.`type` is not NULL and new_worker_id in ()
        // 4. left join allWorker表获取用户详细信息
        // status =true => 已鼓励人员
        List<Map<String, Object>> nonEncourageList;
        if (pageQuery.getCondition().getStatus()) {
            nonEncourageList = tbCareInfoMapper.getEncourageList(userId);
        } else {
            nonEncourageList = tbCareInfoMapper.getNonEncourageList(userId);
        }
        List<NewWorkerDTO> newWorkerDTOS = JSONArray.parseArray(JSONArray.toJSONString(nonEncourageList), NewWorkerDTO.class);
        for (NewWorkerDTO newWorkerDTO : newWorkerDTOS) {
            // 获取与该新员工的关系
            String type = getRelateType(newWorkerDTO, oldWorker);
            newWorkerDTO.setRelateType(type);
            LambdaQueryWrapper<TbOfferWorker> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(TbOfferWorker::getRegularWorkerId, newWorkerDTO.getWorkerId());
            queryWrapper.last("limit 1");
            TbOfferWorker offerWorker = tbOfferWorkerService.getBaseMapper().selectOne(queryWrapper);
            if (offerWorker != null) {
                String workerIntroduce = offerWorker.getWorkerIntroduce();
                newWorkerDTO.setIntroduce(workerIntroduce);
            }
            // TODO 优化
            SdDept sdDept = sdDeptService.getBaseMapper().selectById(newWorkerDTO.getDirectDeptId());
            newWorkerDTO.setDeptName(sdDept.getDeptName());
            newWorkerDTO.clearSensitiveData();
        }
        PageInfo<NewWorkerDTO> pageInfo = page.toPageInfo();
        pageInfo.setList(newWorkerDTOS);
        return pageInfo;
    }

    @Override
    public PageInfo<NewWorkerDTO> getReceiveEncourageList(PageQueryDTO<TbCareEncourageVO> pageQuery) {
        Page<NewWorkerDTO> page = PageHelper.startPage(pageQuery.getPageNum(), pageQuery.getPageSize());
        // 1 获取操作人
        String userId = commService.getLoginUserId();
        SdAllWorker newWorker = commService.getAllWorkerDoFromLocalCache(userId);
        // 获取收到的鼓励的信息（人+鼓励语句）
        // 1. 获取鼓励表中，新员工是自己 且 不是忽略的 全部careInfoIds
        // 2. left join careInfo表获取 type 等信息
        // 3. left join allWorker 获取用户信息
        List<Map<String, Object>> receiveEncourageList = tbCareEncourageMapper.getReceiveEncourageList(userId);
        List<NewWorkerDTO> oldWorkerDTOS = JSONArray.parseArray(JSONArray.toJSONString(receiveEncourageList), NewWorkerDTO.class);
        for (NewWorkerDTO oldWorkerDTO : oldWorkerDTOS) {
            // 获取与该老员工的关系
            // TODO 绩效优秀的通知，前端新员工侧如何显示该提示
            String type = getRelateType(oldWorkerDTO, newWorker);
            oldWorkerDTO.setRelateType(type);
            LambdaQueryWrapper<TbOfferWorker> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(TbOfferWorker::getRegularWorkerId, oldWorkerDTO.getWorkerId());
            queryWrapper.last("limit 1");
            TbOfferWorker offerWorker = tbOfferWorkerService.getBaseMapper().selectOne(queryWrapper);
            if (offerWorker != null) {
                String workerIntroduce = offerWorker.getWorkerIntroduce();
                oldWorkerDTO.setIntroduce(workerIntroduce);
            }
            // TODO 优化
            SdDept sdDept = sdDeptService.getBaseMapper().selectById(oldWorkerDTO.getDirectDeptId());
            oldWorkerDTO.setDeptName(sdDept.getDeptName());
            oldWorkerDTO.clearSensitiveData();
        }
        PageInfo<NewWorkerDTO> pageInfo = page.toPageInfo();
        pageInfo.setList(oldWorkerDTOS);
        return pageInfo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insert(TbCareEncourageVO tbCareEncourageVO) {
        TbCareEncourage tbCareEncourage = new TbCareEncourage();
        BeanUtils.copyProperties(tbCareEncourageVO, tbCareEncourage);

        if (!StringUtils.hasText(tbCareEncourage.getCareInfoId())) {
            throw new AppBusinessException("id不能为空");
        }
        // 未忽略&&没填写鼓励内容
        if (!tbCareEncourage.getIgnoreFlag() && !StringUtils.hasText(tbCareEncourage.getStatement())) {
            throw new AppBusinessException("请填写鼓励语句");
        }
        // 查询TbCareEncourage是否存在
        Integer count = lambdaQuery().eq(TbCareEncourage::getCareInfoId, tbCareEncourage.getCareInfoId()).count();
        if (count > 0) {
            throw new AppBusinessException("请勿重复鼓励");
        }
        // 查询tbCareInfo是否存在
        TbCareInfo careInfo = new LambdaQueryChainWrapper<TbCareInfo>(tbCareInfoMapper)
                .eq(TbCareInfo::getId, tbCareEncourage.getCareInfoId())
                .one();
        if (careInfo == null) {
            throw new AppBusinessException("不存在该数据");
        }
        if (!careInfo.getOldWorkerId().equals(commService.getLoginUserId())) {
            throw new AppBusinessException("无法操作此数据");
        }
        tbCareEncourage.setNewWorkerId(careInfo.getNewWorkerId());
        tbCareEncourage.setOldWorkerId(careInfo.getOldWorkerId());

        this.save(tbCareEncourage);

        TbCareNoticeSetting weChatTitle = tbCareNoticeSettingService.selectOne(TbCareNoticeSetting.SettingType.WECHAT_CONTENT, "新员工侧标题");
        TbCareNoticeSetting weChatContent = tbCareNoticeSettingService.selectOne(TbCareNoticeSetting.SettingType.WECHAT_CONTENT, "新员工侧正文");
        try {
            // 发送企微消息
            weChatUtils.sendWeChatImageMsg("z22968",
                    weChatTitle.getTextValue(),
                    weChatContent.getTextValue() + "( " + careInfo.getNewWorkerId() + " )",
                    weChatUtils.getWeChatOpenUrl(careReceiveUrl));
            // TODO 推送到队列中
        } catch (Exception e) {
            log.info("发送企业微信消息发生错误", e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchInsert(TbCareEncourageVO tbCareEncourageVO) {
        List<String> careInfoIdList = tbCareEncourageVO.getCareInfoIdList();
        if (CollectionUtils.isEmpty(tbCareEncourageVO.getCareInfoIdList())) {
            throw new AppBusinessException("id不能为空！");
        }
        // 未忽略&&没填写鼓励内容
        if (!tbCareEncourageVO.getIgnoreFlag() && !StringUtils.hasText(tbCareEncourageVO.getStatement())) {
            throw new AppBusinessException("请填写鼓励语句");
        }
        for (String careInfoId : careInfoIdList) {
            TbCareEncourageVO tmp = new TbCareEncourageVO();
            BeanUtils.copyProperties(tbCareEncourageVO, tmp);
            tmp.setIgnoreFlag(false);
            tmp.setCareInfoId(careInfoId);
            insert(tmp);
        }
    }

    /**
     * 获取新老员工关系
     *
     * @param newWorkerDTO
     * @param oldWorker
     * @return java.lang.String
     * @author z22968
     * @date 2022-06-20 09:30
     */
    private String getRelateType(NewWorkerDTO newWorkerDTO, SdAllWorker oldWorker) {
        if (newWorkerDTO.getType().equals(CareInfoType.EXCELLENT_PERFORMANCE)) {
            // 绩效优秀
            return TbCareInfo.RelateType.EXCELLENT_PERFORMANCE.getName();
        } else if (newWorkerDTO.getDept4id() != null && oldWorker.getDept4id() != null && newWorkerDTO.getDept4id().intValue() == oldWorker.getDept4id().intValue()) {
            // 有四级部门，且相同
            return TbCareInfo.RelateType.SAME_DEPT.getName();
        } else if (newWorkerDTO.getDept3id() != null && oldWorker.getDept3id() != null && newWorkerDTO.getDept3id().intValue() == oldWorker.getDept3id().intValue()) {
            // 有三级部门，且相同
            return TbCareInfo.RelateType.SAME_DEPT.getName();
        } else if (newWorkerDTO.getDept2id() != null && oldWorker.getDept2id() != null && newWorkerDTO.getDept2id().intValue() == oldWorker.getDept2id().intValue()) {
            // 有二级部门，且相同
            return TbCareInfo.RelateType.SAME_DEPT.getName();
        } else if (newWorkerDTO.getDept1id() != null && oldWorker.getDept1id() != null && newWorkerDTO.getDept1id().intValue() == oldWorker.getDept1id().intValue()) {
            // 有一级部门，且相同
            return TbCareInfo.RelateType.SAME_DEPT.getName();
        } else if (StringUtils.hasText(newWorkerDTO.getGraduateSchool())
                && StringUtils.hasText(oldWorker.getGraduateSchool())
                && newWorkerDTO.getGraduateSchool().equals(oldWorker.getGraduateSchool())) {
            // 最高学历学校不为空，且相同
            return TbCareInfo.RelateType.SCHOOL_FELLOW.getName();
        } else if (StringUtils.hasText(newWorkerDTO.getCertificateNoTopSix())
                && StringUtils.hasText(oldWorker.getCertificateNoTopSix())
                && newWorkerDTO.getCertificateNoTopSix().substring(0, 3).equals(oldWorker.getCertificateNoTopSix().substring(0, 3))) {
            // 身份证前4为不为空，且相同
            return TbCareInfo.RelateType.SAME_BIRTH_PLACE.getName();
        } else {
            return TbCareInfo.RelateType.SAME_WORK_PLACE.getName();
        }
    }
}
